package com.dong.arithmetic.tree;

import sun.reflect.generics.tree.Tree;

/**
 * 前序遍历：根--->左--->右
 *
 * @author jianyang206881
 * @date 2018/7/23
 */
public class DLR extends CreateTree {
    private TreeNote treeNote;

    public static void main(String[] args) {
        DLR dlr = new DLR();
        TreeNote treeNote = dlr.create(14);

        dlr.traversal(treeNote, null);
        System.out.println("\n");

        dlr.traversal(treeNote, 5);
        System.out.println("\ntraversal: " + dlr.treeNote.getValue());

        TreeNote nextNote = dlr.next(dlr.treeNote);
        System.out.println("\nnext: " + (nextNote == null ? null : nextNote.getValue()));
    }

    /**
     * 返回下一个节点
     *
     * @param treeNote 当前节点
     * @return 下一个节点
     */
    private TreeNote next(TreeNote treeNote) {
        // 判断左节点
        TreeNote leftNote = treeNote.getLeft();
        if (leftNote != null) {
            return leftNote;
        }

        // 判断右节点
        TreeNote rightNote = treeNote.getRight();
        if (rightNote != null) {
            return rightNote;
        }

        // 取父节点的右节点
        TreeNote parentNote = treeNote.getParent();
        return parentNote.getRight();
    }

    /**
     * 遍历并返回指定节点
     *
     * @param treeNote 数
     * @param value    节点值
     */
    private void traversal(TreeNote treeNote, Integer value) {
        if (value != null && value.equals(treeNote.getValue())) {
            this.treeNote = treeNote;
            return;
        }
        if (this.treeNote != null) {
            return;
        }

        System.out.print(treeNote.getValue() + " ");

        if (treeNote.getLeft() != null) {
            this.traversal(treeNote.getLeft(), value);
        }

        if (treeNote.getRight() != null) {
            this.traversal(treeNote.getRight(), value);
        }
    }

}
